package com.example.fangwei.utilsapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.fangwei.utilsapp.alioss.OssManager;
import com.example.fangwei.utilsapp.convenientbanner.ConvenientBannerActivity;
import com.example.fangwei.utilsapp.linphone.LinphoneManager;
import com.example.fangwei.utilsapp.linphone.LinphonePreferences;
import com.example.fangwei.utilsapp.linphone.LinphoneService;
import com.example.fangwei.utilsapp.rounddiskview.RoundDiskViewActivity;
import com.example.fangwei.utilsapp.textview.AutoScrollTextViewActivity;
import com.example.fangwei.utilsapp.viewpager.ClipViewPagerActivity;

import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneCoreException;
import org.linphone.core.LinphoneCoreListenerBase;
import org.linphone.core.LinphoneProxyConfig;

import java.io.File;

import me.shenfan.updateapp.UpdateService;

import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private Button btn_clipViewPager,btn_roundDiskView,btn_textView,btn_convenientBanner;
    private Button btn_downloadApk;
    private String downloadUrl = "https://dl.jie360.com.cn/qhh/v1.0.3/qhh_v1.0.3.apk";
    private Button btn_downLoad;
    private Button btn_upload;
    public static MainActivity instance;
    private Button btn_register;
    private Button btn_call;
    private Button btn_hangUp;
    private Handler handler = null;
    private LinphoneCoreListenerBase mListener;
    private Button btn_delete;
    private boolean isRegister = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(Intent.ACTION_MAIN).setClass(this,LinphoneService.class));
        instance = this;
        handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setContentView(R.layout.activity_main);
                initView();
            }
        }, 2000);

    }

    public static final boolean isInstanciated() {
        return instance != null;
    }

    public static final MainActivity instance() {
        if (instance != null)
            return instance;
        throw new RuntimeException("LinphoneActivity not instantiated yet");
    }

    private void initView() {
        btn_clipViewPager = ((Button) findViewById(R.id.btn_clipViewPager));
        btn_clipViewPager.setOnClickListener(this);
        btn_roundDiskView = ((Button) findViewById(R.id.btn_roundDiskView));
        btn_roundDiskView.setOnClickListener(this);
        btn_textView = ((Button) findViewById(R.id.btn_textView));
        btn_textView.setOnClickListener(this);
        btn_convenientBanner = ((Button) findViewById(R.id.btn_convenientBanner));
        btn_convenientBanner.setOnClickListener(this);
        btn_downloadApk = ((Button) findViewById(R.id.btn_update));
        btn_downloadApk.setOnClickListener(this);
        btn_downLoad = ((Button) findViewById(R.id.btn_download));
        btn_downLoad.setOnClickListener(this);
        btn_upload = ((Button) findViewById(R.id.btn_upload));
        btn_upload.setOnClickListener(this);
        btn_register = ((Button) findViewById(R.id.btn_register));
        btn_register.setOnClickListener(this);
        btn_call = ((Button) findViewById(R.id.btn_call));
        btn_call.setOnClickListener(this);
        btn_hangUp = ((Button) findViewById(R.id.btn_hangUp));
        btn_hangUp.setOnClickListener(this);
        btn_delete = ((Button) findViewById(R.id.btn_delete));
        btn_delete.setOnClickListener(this);


        LinphoneManager.getLc().addListener(mListener = new LinphoneCoreListenerBase(){
            @Override
            public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
                super.callState(lc, call, state, message);
                Log.e(TAG, "callState: " + state + " ---" + "message = " +message);
            }

            @Override
            public void registrationState(LinphoneCore lc, LinphoneProxyConfig cfg, LinphoneCore.RegistrationState state, String smessage) {
                super.registrationState(lc, cfg, state, smessage);
                Log.e(TAG, "registrationState: " + state.toString());
                if(state.toString().equals("RegistrationOk")){
                    isRegister = true;
                }else {
                    isRegister = false;
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_clipViewPager:
                intent = new Intent(this, ClipViewPagerActivity.class);
                break;
            case R.id.btn_roundDiskView:
                intent = new Intent(this, RoundDiskViewActivity.class);
                break;
            case R.id.btn_textView:
                intent = new Intent(this, AutoScrollTextViewActivity.class);
                break;
            case R.id.btn_convenientBanner:
                intent = new Intent(this, ConvenientBannerActivity.class);
                break;
            case R.id.btn_update://软件下载
                UpdateService.Builder.create(downloadUrl).build(this);
                break;
            case R.id.btn_download:
                intent = new Intent(this,DownLoadActivity.class);
                break;
            case R.id.btn_upload:
                upload();
                break;
            case R.id.btn_register:
                syncAccount("6004","Zc123456","192.168.9.99");
                break;
            case R.id.btn_call:
                outCallPhone("917682309830");
                break;
            case R.id.btn_hangUp:
                hangUp();
                break;
            case R.id.btn_delete:
                if(isRegister){
                    LinphonePreferences mPref = LinphonePreferences.instance();
                    mPref.deleteAccount(0);
                }
                break;
        }
        if (null != intent){
            startActivity(intent);
        }
    }

    /**
     * 上传文件
     */
    private void upload() {
        final ProgressDialog dialog = new ProgressDialog(this);//展示上传进度
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        String endPoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String bucketName = "smartu";
        String accessKeyId = "";
        String accessKeySecret = "";

        OssManager ossManager = OssManager.getOssManager(this, endPoint, bucketName, accessKeyId, accessKeySecret);
        ossManager.setOnUploadListener(new OssManager.OnUploadListener() {
            @Override
            public void onProgress(int progress) {
                dialog.setProgress(progress);
            }

            @Override
            public void onUploadResult(boolean result) {
                dialog.dismiss();
                String s = result?"成功":"失败";
                Log.e("文件上传" ,"上传"  + s + result);
                Toast.makeText(MainActivity.this, "上传" + s, Toast.LENGTH_SHORT).show();
            }
        });

        String name = "test.jpg";
        String filePath = getExternalStorageDirectory() +"/zcTakePhoto.jpg";
        File file = new File(filePath);
        if (file.exists()){
            ossManager.upload(name,filePath);
            dialog.show();
        }


    }


    /**
     * linPhone
     * 拨打指定电话
     * @param number
     */
    public void outCallPhone(String number){
        String to = String.format("sip:%s@%s",number,"192.168.9.99");
        LinphoneManager.getInstance().newOutgoingCall(to, "");
        LinphoneManager.getLc().enableSpeaker(true);
    }

    /**
     * linPhone
     * 注册
     * @param username 用户名
     * @param password 密码
     * @param domain 域名
     */
    public void syncAccount(String username, String password, String domain){
        LinphonePreferences mPrefs = LinphonePreferences.instance();
        if (mPrefs.isFirstLaunch()) {
            mPrefs.setAutomaticallyAcceptVideoRequests(true);
            mPrefs.enableVideo(true);
        }
        int nbAccounts = mPrefs.getAccountCount();
        if (nbAccounts > 0) {
            String nbUsername = mPrefs.getAccountUsername(0);
            if (nbUsername != null && !nbUsername.equals(username)) {
                mPrefs.deleteAccount(0);
                saveNewAccount(username, password, domain);
            }
        } else {
            saveNewAccount(username, password, domain);
            mPrefs.firstLaunchSuccessful();
        }
    }

    /**
     * linPhone
     * 保存用户
     * @param username 用户名
     * @param password 密码
     * @param domain 域名
     */
    private void saveNewAccount(String username, String password, String domain) {
        LinphonePreferences.AccountBuilder builder = new LinphonePreferences.AccountBuilder(LinphoneManager.getLc())
                .setUsername(username)
                .setDomain(domain)
                .setPassword(password)
                .setDisplayName("")
                .setTransport(LinphoneAddress.TransportType.LinphoneTransportUdp);

        try {
            builder.saveNewAccount();
        } catch (LinphoneCoreException e) {
            Log.e("123456",e.getMessage());
        }
    }


    /**
     * linPhone
     * 挂断电话
     */
    private void hangUp() {
        LinphoneCore lc = LinphoneManager.getLc();
        LinphoneCall currentCall = lc.getCurrentCall();

        if (currentCall != null) {
            lc.terminateCall(currentCall);
        } else if (lc.isInConference()) {
            lc.terminateConference();
        } else {
            lc.terminateAllCalls();
        }
    }



    //测试下分支上传
    //这里是主分支

    //这里是测试分支
    //现在往测是分支提点东西

}
